package cn.iocoder.yudao.module.system.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.service.userretention.UserRetentionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 批量用户留存率计算定时任务
 * 
 * 用于批量计算指定日期范围内的用户留存率数据
 * 参数格式：startDate,endDate (例如：2024-01-01,2024-01-31)
 *
 * @author 系统
 */
@Component
@Slf4j
public class UserRetentionBatchCalculationJob implements JobHandler {

    @Resource
    private UserRetentionService userRetentionService;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        log.info("开始执行批量用户留存率计算定时任务，参数：{}", param);
        
        try {
            LocalDate startDate;
            LocalDate endDate;
            
            if (StringUtils.hasText(param)) {
                // 解析参数
                String[] dates = param.split(",");
                if (dates.length != 2) {
                    throw new IllegalArgumentException("参数格式错误，应为：startDate,endDate");
                }
                
                startDate = LocalDate.parse(dates[0].trim(), DATE_FORMATTER);
                endDate = LocalDate.parse(dates[1].trim(), DATE_FORMATTER);
            } else {
                // 默认计算最近30天
                endDate = LocalDate.now().minusDays(1);
                startDate = endDate.minusDays(29);
            }
            
            log.info("批量计算留存率，日期范围：{} 到 {}", startDate, endDate);
            
            // 执行批量留存率计算
            userRetentionService.batchCalculateRetentionRate(startDate, endDate);
            
            String result = String.format("批量用户留存率计算完成，日期范围：%s 到 %s", 
                                         startDate, endDate);
            log.info(result);
            
            return result;
        } catch (Exception e) {
            log.error("批量用户留存率计算定时任务执行失败", e);
            throw e;
        }
    }
}